package com.yuncheng.spcyApi.flowService;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.YlqxFlowConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxJob;
import com.yuncheng.spcyApi.entity.SpcySqsxXpjl;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.service.impl.YcSysUserServiceImpl;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.jcy.RsHcyVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.util.*;

@Component(value = "YlqxFlowService")
public class YlqxFlowService extends FlowService{

    @Resource
    @Lazy
    private YlqxFlowConstant flowConstant;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISysUserFgldService sysUserFgldService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private YcSysUserServiceImpl ycSysUserService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    @Lazy
    private BusService busService;


    //初始化任务
    public Result initJob(String sqsxId, CurrentUserVo currentUser){
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxId));
        if (CollectionUtils.isNotEmpty(jobList)){
            return Result.error("当前申请事项，已经初始化了");
        }

        Result result = this.initJob(flowConstant, sqsxId, currentUser);
        if (!result.isSuccess()){
            return result;
        }else {
            SpcySqsxJob job = (SpcySqsxJob) result.getResult();
            if (job != null) {
                String nextNodeSmsContent = busService.getNextNodeSmsContent(job, null);
                busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFlcmc()+"-"+job.getFhjmc(),nextNodeSmsContent);
            }
        }
        return result;
//        return this.initJob(flowConstant,sqsxId,currentUser);
    }

    /**
     * 提交当前环节的待办记录
     *  @param sqsxId 申请事项id
     *  @param jobId 当前环节id
     *  @param opinion 办理意见
     */
    public Result passJob(String sqsxId, String jobId, String opinion,String nextNodeName,String nextNodeDbrIds){
        //处理业务表的逻辑
        Result httpResult = this.passJob(flowConstant, sqsxId, jobId, opinion, nextNodeName, nextNodeDbrIds);
        return httpResult;
    }

    /**
     *
     * @param job
     * @param currentUser
     */
    private Result doJob(SpcySqsxJob job, CurrentUserVo currentUser, String opinion){
        String blrId = "";
        String blr = "";
        String blbm = "";
        if (currentUser != null) {
            blrId = currentUser.getId();
            blr = currentUser.getName();
            blbm = currentUser.getOrgName();
        }
        if (job == null){
            return Result.error("当前流程任务不存在，请重试");
        }
        if(SpcyConstant.BLZT_YB.equals(job.getFblzt())){
            return Result.error("当前任务已提交");
        }
        if(StringUtils.isBlank(job.getFdbrid())){
            return Result.error("当前任务未指定办理人");
        }
        if(!job.getFdbrid().contains(blrId)){
            return Result.error("当前登录用户无此任务的办理权限");
        }
        // 办理方式 竞争办理 、多人线性办理 、多人并行办理
        String blfs = job.getFblfs();
        if(StringUtils.isBlank(blfs)||blfs.equals(SpcyConstant.BLFS_DRJJ)){
            job.setFblr(blr);
            job.setFblsj(new Date());
            job.setFblyj(opinion);
            job.setFblzt(SpcyConstant.BLZT_YB);
            job.setFbllx(SpcyConstant.BLLX_BL);
            job.setFblbm(blbm);

            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }else if(blfs.equals(SpcyConstant.BLFS_DRXX)  || blfs.equals(SpcyConstant.BLFS_DRBX)){
            //先根据多个人线性和多人并行的逻辑获得下一办理人
            String nextBlrId ="";
            String nextBlr ="";
            if(blfs.equals(SpcyConstant.BLFS_DRXX)){
                String ydbrIds[] = job.getFydbrid().split(",");
                String ydbrs[] = job.getFydbr().split(",");
                for (int i=0;i<ydbrIds.length;i++){
                    String dbrId = ydbrIds[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(dbrId.equals(blrId)){
                        if(i+1<ydbrIds.length){
                            nextBlrId=ydbrIds[i+1];
                            nextBlr=ydbrs[i+1];
                            break;
                        }
                    }
                }
            }else{
                String dbrIds[] = job.getFdbrid().split(",");
                String dbrs[] = job.getFdbr().split(",");
                for (int i=0;i<dbrIds.length;i++){
                    String dbrId = dbrIds[i];
                    String dbr = dbrs[i];
                    //不考虑办理人id重复出现（一个人办多次）的情况
                    if(!dbrId.equals(blrId)){
                        nextBlrId=nextBlrId+(StringUtils.isBlank(nextBlrId)?"":",")+dbrId;
                        nextBlr=nextBlr+(StringUtils.isBlank(nextBlr)?"":",")+dbr;
                    }
                }
            }

            //如果存在下一办理人 就继续待办，多人办理意见用@@分隔，办理时间、办理人、意见 用|分隔
            job.setFblr(blr);
            job.setFblsj(new Date());
            String blyj=(job.getFblyj()==null?"":job.getFblyj())+(StringUtils.isBlank(job.getFblyj())?"":"@@")+ DateConversionUtils.DateToString(new Date()) +"|"+blr+"|"+ opinion;
            job.setFblyj(blyj);
            if(StringUtils.isBlank(nextBlrId)){
                job.setFblzt(SpcyConstant.BLZT_YB);
                job.setFbllx(SpcyConstant.BLLX_BL);
                job.setFblbm(blbm);
            }else{
                job.setFblzt(SpcyConstant.BLZT_DB);
                job.setFdbrid(nextBlrId);
                job.setFdbr(nextBlr);
            }
            spcySqsxJobService.updateById(job);
            return Result.ok(job);
        }
        return Result.error("待办任务未指定办理方式");
    }

    /**
     *
     * @param sqsxId
     * @param currentJob
     * @param currentUser
     * @param nextNodeName
     * @param nextNodeDbrIds
     * @return
     */
    public Result createNextJob(String sqsxId,SpcySqsxJob currentJob, CurrentUserVo currentUser,String nextNodeName,String nextNodeDbrIds){
        if (currentJob != null) {
            nextNodeName = getNextNodeName(currentJob.getFhjmc(), nextNodeName);
        }else {
            if (StringUtils.isBlank(nextNodeName)){
                return Result.error("下环节不能为空");
            }
        }
        if(nextNodeName.equals(YlqxFlowConstant.HJMC_LCJS)){
            SpcySqsxJob job = new SpcySqsxJob();
            job.setFhjmc(nextNodeName);
            SpcySqsxBasic basic = spcySqsxBaiscService.getById(sqsxId);
            basic.setFlczt(SpcyConstant.LCZT_LCJS);
            spcySqsxBaiscService.updateById(basic);
            return Result.ok("操作成功");
        }
        Map map = this.getNodeDbr(sqsxId,nextNodeName,nextNodeDbrIds);
        nextNodeDbrIds = map.get("dbrId").toString();
        String nextNodeDbrs = map.get("dbr").toString();
        if(StringUtils.isBlank(nextNodeDbrIds)){
            return Result.error("获取不到下一环节待办人");
        }
        SpcySqsxJob job = new SpcySqsxJob();
        job.setId(GetUuIdUtils.NotReplaceUuId());
        if(currentJob != null){
            job.setFsyhjid(currentJob.getId());
        }
        job.setFpid(sqsxId);
        job.setFhjmc(nextNodeName);
        if (currentUser != null) {
            job.setFfsrid(currentUser.getId());
            job.setFfsrmc(currentUser.getName());
        }
        job.setFfssj(new Date());

        job.setFdbrid(nextNodeDbrIds);
        job.setFdbr(nextNodeDbrs);
        job.setFydbrid(nextNodeDbrIds);
        job.setFydbr(nextNodeDbrs);

        // job.setFblfs(YlqxFlowConstant.getBlfs(nextNodeName));
        job.setFblzt(SpcyConstant.BLZT_DB);
        job.setFbllx(SpcyConstant.BLLX_DB);
        job.setFlcmc(flowConstant.getFlowName());
        spcySqsxJobService.save(job);
        return Result.ok(job);
    }

    /**
     *
     * @param currentNodeName 可为空(如果为空，nextNodeName不为空)
     * @param nextNodeName 可为空(如果为空，currentNodename不为空)
     * @return
     */
    private String getNextNodeName(String  currentNodeName,String nextNodeName){
        if (StringUtils.isNotBlank(nextNodeName)){
            return nextNodeName;
        }else{
            return flowConstant.getNextNodeName(currentNodeName);
        }
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String sqsxid,String nodeName, String dbrIds){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        if(StringUtils.isNotBlank(dbrIds)){
            dbr = getDbrsByIds(dbrIds);
            dbrId = dbrIds;
        }else{

            // 任务录入
            if (nodeName.equals(YlqxFlowConstant.HJMC_RWLR)){
                // 经办人
                Map kzMap = getKsjbrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 任务受理
            if (nodeName.equals(YlqxFlowConstant.HJMC_RWSL)){
                // 科室负责人
                Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 任务分配
            if (nodeName.equals(YlqxFlowConstant.HJMC_RWFP)){
                // 部门主管
                Map kzMap = getbmzgByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 方案制作
            if (nodeName.equals(YlqxFlowConstant.HJMC_FAZZ)){
                // 经办人
                Map kzMap = getKsjbrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 查验方案审核
            if (nodeName.equals(YlqxFlowConstant.HJMC_FASH)){
                // 科室负责人
                Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 审评方案审核
            if (nodeName.equals(YlqxFlowConstant.HJMC_SP_FASH)){
                // 科室负责人
                Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 查验方案审批
            if (nodeName.equals(YlqxFlowConstant.HJMC_FASP)) {
                // 分管领导
                Map kzMap = getKsFgldByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 审评方案审批
            if (nodeName.equals(YlqxFlowConstant.HJMC_SP_FASP)) {
                // 分管领导
                Map kzMap = getKsFgldByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 现场检查
            if (nodeName.equals(YlqxFlowConstant.HJMC_XCJC)){
                Map xcjcMap = getXcjcRyBySqsxId(sqsxid,SpcyConstant.FLOW_TYPE_CY);
                dbrId = xcjcMap.get("dbrId").toString();
                dbr = xcjcMap.get("dbr").toString();
            }

            // 技术审评
            if (nodeName.equals(YlqxFlowConstant.HJMC_JSSP)){
                Map xcjcMap = getXcjcRyBySqsxId(sqsxid,SpcyConstant.FLOW_TYPE_SP);
                dbrId = xcjcMap.get("dbrId").toString();
                dbr = xcjcMap.get("dbr").toString();
            }

            // 综合评定
            if (nodeName.equals(YlqxFlowConstant.HJMC_ZHSC)){
                Map zbrMap = getZbrBySqsxId(sqsxid);
                dbrId = zbrMap.get("dbrId").toString();
                dbr = zbrMap.get("dbr").toString();
            }

            // 科室复核
            if (nodeName.equals(YlqxFlowConstant.HJMC_KSFH)){
                // 经办人
                Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

            // 移送确认
            if (nodeName.equals(YlqxFlowConstant.HJMC_YSQR)) {
                // 分管领导
                Map kzMap = getKsFgldByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }

        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取当前环节待办人
    public Map getNodeDbr(String nodeName, String dbrIds){
        return this.getNodeDbr(null,nodeName,dbrIds);
    }

    // 根据待办人id，获取名称拼接起来
    private String getDbrsByIds(String dbrIds){
        //把待办人按id查出来  把名字拼起来
        String dbr = "";
        List<String> dbrIdsList = Arrays.asList(dbrIds.split(","));
        List<YcSysUser> sysUserList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dbrIdsList)){
            sysUserList = ycSysUserService.listByIds(dbrIdsList);
        }

        if (CollectionUtils.isNotEmpty(sysUserList)){
            for (YcSysUser user : sysUserList){
                dbr += user.getRealname() + ",";
            }
        }

        return dbr;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 经办人
    public Map getKsjbrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_JBR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 部门主管
    public Map getbmzgByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_BMZG);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取对应科室的 分管领导
    public Map getKsFgldByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        YcSysUser fgldUserBydept = sysUserFgldService.getFgldUserBydept(deptName);
        if (fgldUserBydept != null) {
            dbrId = fgldUserBydept.getId();
            dbr = fgldUserBydept.getRealname();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取主办人
    public Map getZbrBySqsxId(String sqsxId){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        SpcySqsxBasic basic = spcySqsxBaiscService.getById(sqsxId);
        if (basic != null && StringUtils.isNotBlank(basic.getFzbr())){
            List<String> userids = Arrays.asList(basic.getFzbr().split(",|，"));
            if (CollectionUtils.isNotEmpty(userids)) {
                for (String uid : userids) {
                    YcSysUser sysUser = ycSysUserService.getById(uid);
                    if (sysUser != null) {
                        if (StringUtils.isBlank(dbrId)) {
                            dbrId += sysUser.getId();
                            dbr += sysUser.getRealname();
                        } else {
                            dbrId += "," + sysUser.getId();
                            dbr += "," + sysUser.getRealname();
                        }
                    }
                }
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取现场检查人员
    public Map getXcjcRyBySqsxId(String sqsxId,String flowType){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        // 同意选派记录
        List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                .eq(SpcySqsxXpjl::getFsqsxid, sqsxId)
                .eq(SpcySqsxXpjl::getFsftyxp, SpcyConstant.XPJL_SFTYXP_YES).eq(SpcySqsxXpjl::getFspcylx,flowType));
        if (CollectionUtils.isNotEmpty(xpjlList)){
            for (SpcySqsxXpjl xpjl : xpjlList){
                String fjcyid = xpjl.getFjcyid();
                RsHcyVo rsHcyVo = new RsHcyVo();
                rsHcyVo.setId(fjcyid);
                List<RsHcyVo> rsHcyList = spcyRsHcyService.getRsHcyList(rsHcyVo);
                if (CollectionUtils.isNotEmpty(rsHcyList)){
                    if (StringUtils.isNotBlank(dbrId)) {
                        dbrId += rsHcyList.get(0).getFuserid() + ",";
                        dbr += rsHcyList.get(0).getRealname() + ",";
                    }else {
                        dbrId += rsHcyList.get(0).getFuserid();
                        dbr += rsHcyList.get(0).getRealname();
                    }
                }
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }
}
